<template>
  <div class="app-container">
    <div class="bg_fff mb_12 pl_14">
      <breadcrumb/>
    </div>
    <div class="content-table">
      <div class="form-content">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
          <el-form-item label="角色组ID" prop="keyword">
            <el-input
                v-model="queryParams.keyword"
                placeholder="请输入角色组名称/ID"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
              <el-option
                  v-for="dict in statusList"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="table-content">
        <div class="table-group">
          <div class="group-left">
            <el-button type="primary" size="mini" @click="selectAll">全选</el-button>
            <el-button type="primary" size="mini" @click="selectInvert">反选</el-button>
          </div>
          <div class="group-right">
            <el-button type="primary" size="mini" @click="deleteAll()" class="delBtn" v-hasPermi="['role:batchDel']">批量删除</el-button>
            <el-button type="primary" size="mini" @click="handleAddOrEdit('add')" v-hasPermi="['role:add']">新增</el-button>

          </div>
        </div>
        <div class="table-big">
          <el-table :data="parentList"
                    ref="allTableData"
                    @selection-change="handleSelectionChange"
                    class="tableHightClass"
                    :max-height="tableHeight"
          >
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column :label="item.label"
                             align="center"
                             v-for="(item,index) in tableColumns"
                             :prop="item.key"
                             v-if="item.visible?item.visible:true"
                             :fixed="item.fixed?item.fixed:false"
            >
              <template slot-scope="scope">
                <div v-if="item.key=='statusType'">
                  <el-switch v-model="scope.row[item.key]" @change="handleStatusChange(scope.row)"
                  ></el-switch>
                </div>
                <div v-else-if="item.key=='status'" class="status">
                  <span class="color-green" v-if="scope.row[item.key]==0">正常</span>
                  <span class="color-red" v-if="scope.row[item.key]==1">停用</span>
                </div>
                <div v-else-if="item.key=='menuTypeName'">
                  <el-tag type="success">{{ scope.row[item.key] }}</el-tag>
                </div>
                <div v-else style="display: inline-block">{{ scope.row[item.key] }}</div>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width"
                             width="120">
              <template slot-scope="scope">
                <div class="group-btn">
                  <el-tooltip content="编辑" placement="top" effect="light" v-hasPermi="['role:edit']">
                    <img src="@/assets/images/tableEdit.png" alt="" @click="handleAddOrEdit('edit',scope.row)">
                  </el-tooltip>
                  <el-tooltip content="删除" placement="top" effect="light" v-hasPermi="['role:del']">
                    <img src="@/assets/images/tableDel.png" alt="" @click="handleDelete(scope.row)">
                  </el-tooltip>
                </div>

              </template>
            </el-table-column>
          </el-table>
          <pagination
              v-show="total>10"
              :total="total"
              :page.sync="queryParams.page"
              :limit.sync="queryParams.num"
              @pagination="getList"
          />
        </div>
      </div>
    </div>
    <addOrEditRole v-if="addOrEditRole" :visableIf.sync="addOrEditRole" :id="id" :dialogType="dialogType" @getList="getList" :pageType="pageType"></addOrEditRole>
  </div>


</template>

<script>
import { getRoleList, roleStatusOpen, roleStatusClose, roleDeleteAll,roleDelete } from '@/api/roles'

export default {
  name: 'roleList',
  components: {
    'addOrEditRole': () => import('./addOrEditRole')
  },
  data() {
    return {
      total: 8,// 表格的总条数
      dialogType: 'add',
      pageType: '2',
      tableHeight: 300,
      addOrEditRole: false,
      id: null,//z角色id
      queryParams: {
        page: 1,
        num: 10,
        keyword:'',//关键字
        status:null,//状态
      },
      statusList: [
        { value: 1, label: '正常' },
        { value: 0, label: '暂停' }
      ],
      parentList: [],
      multipleSelection:[],//全选
      tableColumns: [
        { key: 'id', label: `角色ID`, visible: true },
        { key: 'roleName', label: `角色组名称`, visible: true },
        { key: 'statusType', label: `开关状态`, visible: true },
        { key: 'status', label: `状态`, visible: true },
      ]
    }
  },
  created() {
    this.getList()
  },
  watch: {
    parentList: {
      handler(val) {
        if (val.length > 0) {
          this.getTabelHeight()//获取表格的最大高度
          this.getTableContentHeight()//获取整体的高度
          this.$refs.allTableData.doLayout()
        }

      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    //删除角色组的方法
    handleDelete(row) {
      this.$modal.confirm('是否确认删除选中的角色组？').then(() => {
        roleDelete(row.id).then(res => {
          if (res.code == 1) {
            this.$modal.msgSuccess("删除成功");
            this.handleQuery();
          } else {
            this.$modal.msgError(res.msg);
          }

        })
      }).catch(() => {
        console.log('你取消删除角色组的操作');
      });
    },
    deleteAll() {
      if (this.multipleSelection.length == 0) {
        this.$modal.msgError(`请选择你要删除的角色组！`);
        return false;
      }
      //删除所有
      this.$modal.confirm('是否确认删除选中的角色组？').then(() => {
        let obj = {
          id: this.multipleSelection,
        }
        roleDeleteAll(obj).then(res => {
          this.$modal.msgSuccess("删除成功");
          this.handleQuery();
        })
      }).catch(() => {
        console.log('你取消删除角色组的操作');
      });
    },
    getTableContentHeight() {
      let topHeight = document.querySelector('.table-content').offsetTop
      let windowsHeight = document.body.clientHeight
      document.querySelector('.table-content').style.height = windowsHeight - topHeight - 20 + 'px'
    },
    getTabelHeight() {
      //获取表格的高度
      let topHeight = document.querySelector('.tableHightClass').offsetTop
      let windowsHeight = document.body.clientHeight
      if (this.total > 10) {
        let paginationContainerHeight = document.querySelector('.pagination-container').clientHeight
        this.tableHeight = windowsHeight - topHeight - 20 - paginationContainerHeight - 40
      } else {
        this.tableHeight = windowsHeight - topHeight - 20
      }
    },
    handleAddOrEdit(type, row) {
      if (type == 'add') {
        this.id = null
        this.dialogType = 'add'
      } else {
        this.id = row.id//角色id
        this.dialogType = 'edit'
      }
      this.addOrEditRole = true
    },
    //审核的列表
    getList() {
      this.loading = true
      getRoleList(this.queryParams).then(res => {
        this.parentList = res.data.list
        this.parentList.forEach(item => {
          item.statusType = item.status == 0 ? true : false
        })
        this.total = res.data.count
        this.loading = false
      })
    },
    selectAll() {
      //全选功能,先进行清除状态，然后再选择是全选还是多选
      this.$refs.allTableData.clearSelection();
      this.parentList.forEach((row) => {
        this.$refs.allTableData.toggleRowSelection(row);
      })
    },
    selectInvert() {
      //反选功能
      console.log('已经选',this.multipleSelection);
      let listfiter = this.parentList.filter(item => {
        return this.multipleSelection.indexOf(item.id) == -1;// 不包含选中的
      });
      console.log('反选过滤', listfiter);
      // 然后进行反选
      this.$refs.allTableData.clearSelection();
      if (listfiter && listfiter.length > 0) {
        listfiter.forEach((item) => {
          this.$refs.allTableData.toggleRowSelection(item);
        })
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = [];
      if (val && val.length > 0) {
        val.forEach((item) => {
          this.multipleSelection.push(item.id);
        })
        console.log('multipleSelection', this.multipleSelection);
      }
    },
    //搜索广告计划列表
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    }
    ,
    //重置表单
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleStatusChange(row) {
      console.log('状态', row.status)
      let text = row.status == false ? '暂停' : '启用'
      this.$modal.confirm(`确认要${text}角色（${row.roleName}）吗？`).then(function() {
        if (row.status == false) {
          return roleStatusClose(row.id)
        } else {
          return roleStatusOpen(row.id)
        }
      }).then(() => {
        this.$modal.msgSuccess(text + '成功')
        this.getList()
      }).catch(function() {
        row.status = row.status == 0 ? false : true
      })
    },
    handleCloseDialog() {
      this.$emit('update:visableIf', false)
    }
  }
}
</script>

<style scoped lang="scss">
.form-content {
  padding: 12px;
  background: #fff;
  margin-bottom: 10px;
}

::v-deep .el-dialog__body {
  max-height: calc(100vh - 250px);
  overflow-y: auto;
}

.operate-Big {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 80px;

}

.group-right {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 15px;
}

.status {
  span {
    position: relative;
    padding-left: 15px;

    &:after {
      position: absolute;
      left: 0px;
      width: 9px;
      height: 9px;
      border-radius: 50%;
      content: '';
      top: 50%;
      margin-top: -4.5px;
    }

    &.color-green:after {

      background: #00DD33;


    }

    &.color-red:after {
      background: #D10807;
    }
  }

}
</style>
